package io.jft.doll.room.repository

import io.jft.doll.api.CartApi
import io.jft.doll.api.apiProviderMock
import io.jft.doll.room.entity.remote.CartREntity
import com.g.base.api.ErrorCode
import com.g.base.room.repository.BaseRepository
import com.g.base.room.repository.MockDbLiveData
import com.g.base.room.repository.NetworkBoundResult
import com.google.gson.JsonObject

/**
 * Created by G on 2017/11/13 0013.
 */
class CartRepository : BaseRepository() {
    companion object {
         val cartData by lazy { MockDbLiveData<CartREntity>() }
    }

    private val cartApi by lazy { apiProviderMock.create(CartApi::class.java) }

    fun applyShipping(addressId: String): NetworkBoundResult<CartREntity?> = NetworkBoundResult(
            {
                cartApi.applyShip(JsonObject().apply {
                    addProperty("addressId", addressId)
                })
            },
            onRemoteSucceed = {
                if (it != null)
                    cartData.postValue(it)
            },
            onRemoteFailed = {
                if (it.code == ErrorCode.EMPTY)
                    cartData.postValue(CartREntity())
            })

    fun getCartList() = NetworkBoundResult({ cartApi.getCartList() },
            loadFormDb = { cartData },
            shouldRemote = { cartData.value == null },
            saveRemoteResult = { if (it != null) cartData.postValue(it) },
            onRemoteFailed = {
                if (it.code == ErrorCode.EMPTY)
                    cartData.postValue(CartREntity())
            }
    )

    fun checkOne(id: String, check: Boolean) = NetworkBoundResult(
            {
                cartApi.getCartCheckOne(JsonObject()
                        .apply {
                            addProperty("id", id)
                            addProperty("checked", check)
                        }
                )
            },
            onRemoteSucceed = {
                if (it != null)
                    cartData.postValue(it)
            },
            onRemoteFailed = {
                if (it.code == ErrorCode.EMPTY)
                    cartData.postValue(CartREntity())
            })


    fun checkAll(check: Boolean) = NetworkBoundResult(
            {
                cartApi.getCartCheckAll(JsonObject()
                        .apply {
                            addProperty("checked", check)
                        }
                )
            },
            onRemoteSucceed = {
                if (it != null)
                    cartData.postValue(it)
            },
            onRemoteFailed = {
                if (it.code == ErrorCode.EMPTY)
                    cartData.postValue(CartREntity())
            })
}